import { GlobalParameters } from '#/store';
import { defineStore } from 'pinia';
import { store } from '@/store';
import { GLOBAL_PARAMETERS_KEY } from '@/enums/cacheEnum';
import { getAuthCache, setAuthCache } from '@/utils/auth';

interface GlobalParametersState {
  globalParameters: GlobalParameters[];
}

export const useGlobalParametersStore = defineStore({
  id: 'global-parameters',
  state: (): GlobalParametersState => ({
    // globalParameters
    globalParameters: [],
  }),
  getters: {
    getGlobalParametersList(state): GlobalParameters[] {
      return state.globalParameters.length > 0
        ? state.globalParameters
        : getAuthCache<GlobalParameters[]>(GLOBAL_PARAMETERS_KEY);
    },
  },
  actions: {
    setGlobalParametersList(globalParameters: GlobalParameters[]) {
      this.globalParameters = globalParameters;
      setAuthCache(GLOBAL_PARAMETERS_KEY, globalParameters);
    },
    resetState() {
      this.globalParameters = [];
    },
  },
});

// Need to be used outside the setup
export function useGlobalParametersStoreWithOut() {
  return useGlobalParametersStore(store);
}
